package com.azdebugit.trancation.test.util;

import com.azdebugit.future.vip.executorcompletion.test.BatchContainerExecutor;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * Json工具
 */
public class JsonUtil {

    /** 默认使用jackson */
    public static ObjectMapper mapper;

    static {
        mapper = new ObjectMapper();
        //设置Jackson序列化时只包含不为空的字段
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //设置在反序列化时忽略在JSON字符串中存在，而在Java中不存在的属性
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    public static String toPrettyJsonString(Object value) {
        //打印原始格式不做格式化
        return toJsonString(value);
        /*String jsonString;
        try {
            jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new BizException("Json序列化失败");
        }
        return jsonString;*/
    }

    public static String toJsonString(Object value) {
        String jsonString ="";
        try {
            jsonString = mapper.writeValueAsString(value);
        }catch (Exception e){
            System.out.println("Json序列化失败");
            e.printStackTrace();
        }
        return jsonString;
    }

    public static <T> T fromJsonString(String content,Class<T> valueType) {
        T t = null;
        try {
            t = mapper.readValue(content,valueType);
        } catch (IOException e) {
            System.out.println("Json反序列化失败");
            e.printStackTrace();
        }
        return t;
    }

}